package com.shop.clientorder.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import com.alibaba.fastjson.JSONObject;
import com.shop.clientorder.domain.*;
import com.shop.car.domain.ShopCarDetails;
import com.shop.clientorder.feign.ProductRemote;
import com.shop.clientorder.feign.ShopCarRemote;
import com.shop.common.core.domain.Result;
import com.shop.common.redis.service.RedisService;
import com.shop.common.security.service.TokenService;
import com.shop.product.domain.PmsSkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shop.clientorder.mapper.OmsOrderMapper;
import com.shop.clientorder.service.IOmsOrderService;

import static com.shop.clientorder.constant.RedisConstant.RedisKeyConstants;

/**
 * 订单Service业务层处理
 *
 * @author czb
 * @date 2024-06-25
 */
@Service
public class OmsOrderServiceImpl implements IOmsOrderService
{
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private ShopCarRemote shopCarRemote;
    @Autowired
    private ProductRemote productRemote;
    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;
//    @Autowired
//    private ProductRemote clientOrderRemote;
    /**ml\
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OmsOrder selectOmsOrderById(Long id)
    {
        return omsOrderMapper.selectOmsOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param omsOrder 订单
     * @return 订单
     */
    @Override
    public List<OmsOrder> selectOmsOrderList(OmsOrder omsOrder)
    {
        return omsOrderMapper.selectOmsOrderList(omsOrder);
    }

    /**
     * 新增订单
     *
     * @param orderVo@return 结果
     */
    @Override
    public List<ShopCarDetails> insertOmsOrder(OrderVo orderVo)
    {
        ArrayList<ShopCarDetails> list = new ArrayList<>();
        ArrayList<ShopCarDetails> list1 = new ArrayList<>();
        OmsOrder omsOrder = new OmsOrder();
        extracted(orderVo,list);
        for (ShopCarDetails carDetails : list) {
            //订单校验
            Map<Long, Boolean> booleanLongMap = stockCheckout(carDetails.getSkuId(), carDetails.getDetailsCount());
            for (final Map.Entry<Long, Boolean> entry : booleanLongMap.entrySet()) {
                Boolean value = entry.getValue();
                // 判断结果是否错误
                if (value.equals(false)) {
                    // 中途可查询商品详细信息
                    Result<PmsSkuInfo> info = productRemote.getSkuInfo(entry.getKey());
                    throw new RuntimeException("商品“" + info.getData().getSkuTitle() + "”库存不足");
                }
            }
            Result<ShopCarDetails> shopCarDetailsRemote = shopCarRemote.findShopCarDetails(carDetails.getDetailsId());
            ShopCarDetails details = shopCarDetailsRemote.getData();
            list1.add(details);
        }
        return list1;
//        //异步批量添加订单
//        for (ShopCarDetails carDetails : list) {
//            String orderSn = orderVo.getOrderSn();
//            kafkaTemplate.send("Add_Order",orderSn,carDetails);
//        }

        //异步添加订单详情
/*        for (ShopCarDetails carDetails : list) {
            kafkaTemplate.send("Add_Order_Item",carDetails);
        }*/
    }

    //完成传入参数的切割和分配
    private static void extracted(OrderVo orderVo, ArrayList<ShopCarDetails> list) {
        List<String> ids = orderVo.getIds();
        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            String numMoney = orderVo.getNumAndMoney().get(i);

            // 创建 ShopCarDetails 对象
            ShopCarDetails shopCarDetails = new ShopCarDetails();
            shopCarDetails.setDetailsId(Long.valueOf(id));

            // 处理 numMoney
            String[] split = numMoney.split("\\|");
            shopCarDetails.setDetailsCount(Long.valueOf(split[0]));
            BigDecimal bigDecimal = new BigDecimal(split[1]);
            shopCarDetails.setDetailsTotalMoney(bigDecimal);
            // 将 shopCarDetails 添加到 list 中
            list.add(shopCarDetails);
        }
    }
    //库存校验
    public Map<Long, Boolean> stockCheckout(Long skuId, Long detailsCount) {
        final AtomicReference<Long> stock = new AtomicReference<>(0L);
        // 中途可查询商品详细信息
        Result<PmsSkuInfo> info = productRemote.getSkuInfo(skuId);
        Map<Long, Boolean> booleanLongMap = new HashMap<>();
        // 1. redis获取商品库存
        List<Long> wareIds = redisService.getCacheList(RedisKeyConstants);
        wareIds.forEach(wareId -> {
            String stockString = redisService.getCacheMapValue(
                    /* key */
                    RedisKeyConstants + wareId,
                    /* value */
                    skuId.toString());
            stock.set(JSONObject.parseObject(stockString, Long.class));
        });

        if (null == stock.get()) {
            throw new RuntimeException("该商品“" + info.getData().getSkuTitle() + "”不存在 可联系客服及时供货");
        }
        // 2. 判断数量是否小于库存量
        boolean bool = stock.get() < detailsCount;
        // 2.1. 如果库存量小于需求 返回提示库存不足
        if (bool) {
            booleanLongMap.put(skuId, false);
        }
        // 2.2. 如果库存量大于等于需求 返回提示11
        else {
            booleanLongMap.put(skuId, true);
        }
        return booleanLongMap;
    }

    /**
     * 修改订单
     *
     * @param omsOrder 订单
     * @return 结果
     */
    @Override
    public int updateOmsOrder(OmsOrder omsOrder)
    {
        return omsOrderMapper.updateOmsOrder(omsOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOmsOrderByIds(Long[] ids)
    {
        return omsOrderMapper.deleteOmsOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOmsOrderById(Long id)
    {
        return omsOrderMapper.deleteOmsOrderById(id);
    }

    @Override
    public List<OmsOrder> selectClirentOrderList(OrderReq orderReq) {
        return omsOrderMapper.selectClientOrderList(orderReq);
    }

    @Override
    public int insertOmsOrderNew(OrderItemRequest orderItemRequest) {
        List<OrderDTO> dtoList = orderItemRequest.getDtoList();
        for (OrderDTO orderDTO : dtoList) {
            Long skuId = orderDTO.getSkuId();
            Long detailsNum = orderDTO.getDetailsNum();
            //库存校验
            Long carId = orderDTO.getCarId();
            Long detailsId=orderDTO.getDetailsId();
//            Result<List<ShopCarDetails>> carDetails = shopCarRemote.findShopCarDetails(carId, detailsId);
//            List<ShopCarDetails> shopCarDetails = carDetails.getData();
        }
        return 0;
    }

    @Override
    public Long findOrderIdByOrderSn(String orderSn) {
        return omsOrderMapper.findOrderIdByOrderSn(orderSn);
    }

    @Override
    public int addOrder(OmsOrder omsOrder) {
        int i=omsOrderMapper.addOrder(omsOrder);
        return i;
    }

    @Override
    public Integer findOrderStatusByOrderSn(String orderSn) {
        return omsOrderMapper.findOrderStatusByOrderSn(orderSn);
    }

    @Override
    public void updateOrder(String orderSn) {
        omsOrderMapper.updateOrder(orderSn);
    }

    @Override
    public List<FullAdders> fullAdders(Long userId) {
        return omsOrderMapper.fullAdders(userId);
    }
}